package com.zc.portal.infra.security.handler;

import com.alibaba.fastjson.JSON;
import com.zc.commons.pojo.ResponseData;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class RoleAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest req, HttpServletResponse resp, AccessDeniedException e) throws IOException, ServletException {
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json");
        ResponseData responseData = new ResponseData();
        responseData.setCode(HttpStatus.FORBIDDEN.value());
        responseData.setMessage("无权限！");
        responseData.setData(e.getMessage());
        String jsonString = JSON.toJSONString(responseData);
        PrintWriter printWriter = resp.getWriter();
        printWriter.write(jsonString);
        if (printWriter != null) {
            printWriter.flush();
            printWriter.close();
        }
    }
}
